﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CustomControls;
using Model;
using DataAccess;
using Model.EntityModel;
using System.Collections.ObjectModel;

namespace Project
{
    /// <summary>
    /// Lógica de interacción para RegisterPSicologistReportContent.xaml
    /// </summary>
    public partial class RegisterPSicologistReportContent : UserControl
    {
        public PsicologistReportClass report;
        public long idComplaint;
        public bool modify;
        public SearchComplaintWindow sc;
        public SearchFunctionary search;
        //public FunctionaryInfo employee;
        public Model.EntityModel.Actor actor;

        public RegisterPSicologistReportContent()
        {
            InitializeComponent();
            UIWindowManager.SetWindowTitle(this, "Brigada De Protección a la Familia - RegisterPsicologistReport");
            report = new PsicologistReportClass();
            report.Interventions = new List<string>();
            report.Reasons = new List<string>();
            report.Family = new List<Familiar>();
            //employee = new FunctionaryInfo();
            lbDate.Content = DateTime.Now.ToShortDateString();
            lbTime.Content = DateTime.Now.ToShortTimeString();
            report.Date = DateTime.Now.Date;
            report.Time = DateTime.Now.ToShortTimeString();
            report.Id = PsicologistReportDBAccess.TotalReports + 1;
            tbOtherIntervention.DeactivateBlankValidation();
            tbOtherReason.DeactivateBlankValidation();
            tbAge.DeactivateBlankValidation();
            tbEducation.DeactivateBlankValidation();
            tbName.DeactivateBlankValidation();
            tbOcupation.DeactivateBlankValidation();
            tbRelationtip.DeactivateBlankValidation();
            modify = false;
        }

        public RegisterPSicologistReportContent(PsicologistReportClass rep)
        {
            InitializeComponent();

            UIWindowManager.SetWindowTitle(this, "Brigada De Protección a la Familia - RegisterPsicologistReport");
            report = new PsicologistReportClass();
            report.Interventions = new List<string>();
            report.Reasons = new List<string>();
            modify = true;
            report = rep;
            //employee = new FunctionaryInfo();
            fillInterface();
            tbOtherIntervention.DeactivateBlankValidation();
            tbOtherReason.DeactivateBlankValidation();
            tbAge.DeactivateBlankValidation();
            tbEducation.DeactivateBlankValidation();
            tbName.DeactivateBlankValidation();
            tbOcupation.DeactivateBlankValidation();
            tbRelationtip.DeactivateBlankValidation();
        }

        public void fillInterface()
        {
            tbRecom.Text = report.Recomendations;
            tbFirstContact.Text = report.FirstContact;
            tbBehavior.Text = report.Behavior;
            lbDate.Content = report.Date.ToShortDateString();
            lbTime.Content = report.Time;
            tbChildren.Text = report.Children.ToString();
            string[] conv = report.Convivence.Split(' ');
            tbCant.Text = conv[0];
            cbTiempo.SelectedValue = conv[1];
            cbTypeOfReason.SelectedValue = report.TypeOfReason;
            for (int i = 0; i < report.Interventions.Count; i++)
            {
                listInterventions.Items.Add(report.Interventions[i]);
            }
            for (int i = 0; i < report.Reasons.Count; i++)
            {
                listReasons.Items.Add(report.Reasons[i]);
            }
            for (int i = 0; i < report.Family.Count; i++)
            {
                listAges.Items.Add(report.Family[i].Age);
                listEducation.Items.Add(report.Family[i].Education);
                listNames.Items.Add(report.Family[i].Name);
                listRelations.Items.Add(report.Family[i].Relation);
                listOcupation.Items.Add(report.Family[i].Ocupation);
            }

            idComplaint = report.IdComplaint;
            lbCase.Content = report.IdComplaint;
            Model.EntityModel.Person person = PersonAndActorDataAccess.GetPersonById(report.IdPerson);
            string actorType = PersonAndActorDataAccess.GetActorRTypeByComplaintIdAndPersonId(report.IdPerson, report.IdComplaint);
            cbActorType.SelectedValue = actorType;
            
            /*lbCiPsico.Content = report.CiPsicologist;
            Functionary emp = DataBaseAccess.ReadEmployee(report.CiPsicologist);
            lbPsicologist.Content = emp.Name + emp.PaternalName;
            if (!String.IsNullOrEmpty(emp.MaternalName))
                lbPsicologist.Content += emp.MaternalName;*/
        }

        public void Charge()
        {
            try
            {
                lbCase.Content = idComplaint.ToString();
                cbActorType.SelectedIndex = -1;
            }
            catch
            {
                MessageBox.Show("Error en al obtener datos de nuestra base de datos", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        void getComplaintEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                idComplaint = (sc.Content.Children[0] as SearchComplaint).SelectedComplaintId;
                Charge();
            }
            catch
            {
                MessageBox.Show("Ocurrio un error al obtener el empleado", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void BuscarCaso_Click(object sender, RoutedEventArgs e)
        {
            sc = new SearchComplaintWindow();
            (sc.Content.Children[0] as SearchComplaint).listViewComplaints.MouseDoubleClick += (getComplaintEventHandler);
            sc.ShowDialog();
        }
        /*
        void getEmployeeEventHandler(object sender, RoutedEventArgs e)
        {
            try
            {
                employee = search.Employee;
                lbPsicologist.Content = employee.Name;
                lbCiPsico.Content = employee.CI;
            }
            catch
            {
                MessageBox.Show("Ocurrio un error al obtener el empleado", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            search = new SearchFunctionary();
            search.getEmployee += new RoutedEventHandler(getEmployeeEventHandler);
            search.ShowDialog();
        }
        */
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (cbReason.SelectedIndex != -1)
            {
                ComboBoxItem type = (ComboBoxItem)cbReason.SelectedItem;
                string text = type.Content.ToString();
                if (type.Content.ToString() == "Otros" && !String.IsNullOrEmpty(tbOtherReason.Text))
                {
                    if (!listReasons.Items.Contains(tbOtherReason.Text))
                        listReasons.Items.Add(tbOtherReason.Text);
                }
                else
                {
                    if (!listReasons.Items.Contains(text))
                        listReasons.Items.Add(text);
                }
            }
        }

        private void button4_Click(object sender, RoutedEventArgs e)
        {
            if (cbIntervention.SelectedIndex != -1)
            {
                ComboBoxItem type = (ComboBoxItem)cbIntervention.SelectedItem;
                string text = type.Content.ToString();
                if (type.Content.ToString() == "Otros" && !String.IsNullOrEmpty(tbOtherIntervention.Text))
                {
                    if (!listInterventions.Items.Contains(tbOtherIntervention.Text))
                        listInterventions.Items.Add(tbOtherIntervention.Text);
                }
                else
                {
                    if (!listInterventions.Items.Contains(text))
                        listInterventions.Items.Add(text);
                }
            }
        }

        public void FillPersonInfo()
        {
            if (actor != null)
            {
                Model.EntityModel.Person person = actor.Person;
                lbCi.Content = person.CiPassport.ToString();
                lbName.Content = person.Name;
                lbPaternal.Content = person.PaternalName;
                if (!String.IsNullOrEmpty(person.MaternalName))
                    lbMaternal.Content = person.MaternalName;
            }
            else
            {
                lbCi.Content = "";
                lbName.Content = "";
                lbPaternal.Content = "";
                lbMaternal.Content = "";
            }
        }

        private bool CheckHasError()
        {
            bool res = false;
            foreach (var control in Content.Children)
            {
                GroupBox gp = control as GroupBox;
                if (gp != null)
                {
                    foreach (var ctrl in (gp.Content as Grid).Children)
                    {
                        TextBox tb = ctrl as TextBox;
                        if (tb != null)
                        {
                            tb.GetBindingExpression(TextBox.TextProperty).UpdateSource();
                            if (Validation.GetHasError(tb))
                                res = true;
                        }
                        ValidationComboBox cb = ctrl as ValidationComboBox;
                        if (cb != null)
                        {
                            cb.LostFocusEventHandler(cb, null);
                            if (Validation.GetHasError(cb))
                                res = true;
                        }
                        ValidDatePicker dtp = ctrl as ValidDatePicker;
                        if (dtp != null)
                        {
                            dtp.GetBindingExpression(DatePicker.TextProperty).UpdateSource();
                            dtp.LostFocusEventHandler(dtp, null);
                            if (Validation.GetHasError(dtp))
                                res = true;
                        }
                    }
                }
                
            }
            return res;
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            if(!CheckHasError() && !String.IsNullOrEmpty(lbCase.Content.ToString()) && !String.IsNullOrEmpty(lbCi.Content.ToString()))
            {
                if (listInterventions.Items.Count > 0 && listReasons.Items.Count > 0)
                {
                    fillReport();
                    if (modify)
                    {
                        var grantPermission = new GrantDirectorPermissionWindows();
                        if (grantPermission.ShowDialog() == true)
                        {
                            try
                            {
                                MessageBoxResult result = MessageBox.Show("Guardado Correctamente! Desea imprimir?", "Informacion", MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    var items = new ObservableCollection<UserControl>();
                                    items.Add(new PrintPsicologistReport(report));
                                    items.Add(new PrintPsicologistReportPart2(report));
                                    var a = new PrintPreviewDialogV2(items);
                                    a.ShowDialog();
                                }
                                else
                                {
                                    Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir el reporte posteriormente, entrando a Ver Denuncias, click derecho sobre la denuncia selecciona la opción Ver Informes PSicologicos seleccionando el que desea",
                                                                    "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                                UIWindowManager.CleanWindow(this);
                            }
                            catch
                            {
                                MessageBox.Show("Se produjo un error inesperado");
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            if (PsicologistReportDBAccess.RegisterPsicologistReport(report))
                            {
                                MessageBoxResult result = MessageBox.Show("Citacion Registrada! Desea imprimirla?", "Informacion", MessageBoxButton.YesNo, MessageBoxImage.Question);
                                if (result == MessageBoxResult.Yes)
                                {
                                    var items = new ObservableCollection<UserControl>();
                                    items.Add(new PrintPsicologistReport(report));
                                    items.Add(new PrintPsicologistReportPart2(report));
                                    var a = new PrintPreviewDialogV2(items);
                                    a.ShowDialog();
                                }
                                else
                                {
                                    Xceed.Wpf.Toolkit.MessageBox.Show("Puede imprimir la citacion posteriormente, entrando a Ver Denuncias, click sobre la denuncia selecciona la opción Ver Citaciones seleccionando por fecha la citacion que desea",
                                                                    "Información!", MessageBoxButton.OK, MessageBoxImage.Information);
                                }
                                UIWindowManager.CleanWindow(this);
                            }
                            else
                                MessageBox.Show("Se produjo un error inesperado");
                        }
                        catch
                        {
                            MessageBox.Show("Se produjo un error inesperado");
                        }
                    }
                }
                else
                    MessageBox.Show("Las listas deben contener al menos un elemento");
            }
            else
                MessageBox.Show("Todos los campos marcados con asterisco deben ser llenados");
        }

        public void fillReport()
        {
            if (modify)
            {
                report.Reasons.Clear();
                report.Interventions.Clear();
                report.Family.Clear();
            }
            for (int i = 0; i < listReasons.Items.Count; i++)
            {
                report.Reasons.Add(listReasons.Items[i].ToString());
            }
            for (int i = 0; i < listInterventions.Items.Count; i++)
            {
                report.Interventions.Add(listInterventions.Items[i].ToString());
            }
            for (int i = 0; i < listNames.Items.Count; i++)
            {
                Familiar fam = new Familiar();
                fam.Relation = listRelations.Items[i].ToString();
                fam.Name = listNames.Items[i].ToString();
                fam.Ocupation = listOcupation.Items[i].ToString();
                fam.Education = listEducation.Items[i].ToString();
                fam.Age = Convert.ToInt32(listAges.Items[i].ToString());
                report.Family.Add(fam);
            }
            report.Children = Convert.ToInt32(tbChildren.Text);
            ComboBoxItem type = (ComboBoxItem)cbTiempo.SelectedItem;
            report.Convivence = tbCant.Text + " " + type.Content.ToString();
            report.CiPsicologist = UserControllerAndDataAccess.CurrentLoggedUser.CiEmployee;
            report.IdComplaint = idComplaint;
            report.IdPerson = actor.IdPerson;
            type = (ComboBoxItem)cbTypeOfReason.SelectedItem;
            report.TypeOfReason = type.Content.ToString();
            report.FirstContact = tbFirstContact.Text;
            report.Behavior = tbBehavior.Text;
            report.Recomendations = tbRecom.Text;
        }

        private void cbReason_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBoxItem type = (ComboBoxItem)cbReason.SelectedItem;
            if (type.Content.ToString() == "Otros")
                tbOtherReason.IsEnabled = true;
            else
                tbOtherReason.IsEnabled = false;
        }

        private void cbIntervention_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBoxItem type = (ComboBoxItem)cbIntervention.SelectedItem;
            if (type.Content.ToString() == "Otros")
                tbOtherIntervention.IsEnabled = true;
            else
                tbOtherIntervention.IsEnabled = false;
        }

        private void cbActorType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbActorType.SelectedIndex != -1)
            {
                ComboBoxItem type = (ComboBoxItem)cbActorType.SelectedItem;
                string role = type.Content.ToString();
                actor = PersonAndActorDataAccess.GetActorByTypeAndComplaintId(role, idComplaint);
                FillPersonInfo();
            }
            else
            {
                lbCi.Content = "";
                lbName.Content = "";
                lbPaternal.Content = "";
                lbMaternal.Content = "";
            }
        }

        private void addFamiliar_Click(object sender, RoutedEventArgs e)
        {
            if (!String.IsNullOrEmpty(tbAge.Text) && !String.IsNullOrEmpty(tbOcupation.Text) && !String.IsNullOrEmpty(tbRelationtip.Text) && !String.IsNullOrEmpty(tbName.Text) && !String.IsNullOrEmpty(tbEducation.Text))
            {
                listAges.Items.Add(tbAge.Text);
                tbAge.Text = "";
                listEducation.Items.Add(tbEducation.Text);
                tbEducation.Text = "";
                listNames.Items.Add(tbName.Text);
                tbName.Text = "";
                listRelations.Items.Add(tbRelationtip.Text);
                tbRelationtip.Text = "";
                listOcupation.Items.Add(tbOcupation.Text);
                tbOcupation.Text = "";
            }
            else
                MessageBox.Show("Todos los campos deben ser llenados para agregar aun familiar");
        }

        private void button6_Click(object sender, RoutedEventArgs e)
        {
            if (listReasons.SelectedIndex != -1)
            {
                List<string> aux = new List<string>();
                for (int i = 0; i < listReasons.Items.Count; i++)
                {
                    if (i != listReasons.SelectedIndex)
                        aux.Add(listReasons.Items[i].ToString());
                }
                listReasons.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listReasons.Items.Add(aux[i]);
                }
            }
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            if (listInterventions.SelectedIndex != -1)
            {
                List<string> aux = new List<string>();
                for (int i = 0; i < listInterventions.Items.Count; i++)
                {
                    if (i != listInterventions.SelectedIndex)
                        aux.Add(listInterventions.Items[i].ToString());
                }
                listInterventions.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listInterventions.Items.Add(aux[i]);
                }
            }
        }
        
        private void deleteFamiliar_Click(object sender, RoutedEventArgs e)
        {
            if (listNames.SelectedIndex != -1)
            {
                List<string> aux = new List<string>();

                for (int i = 0; i < listAges.Items.Count; i++)
                {
                    if (i != listNames.SelectedIndex)
                        aux.Add(listAges.Items[i].ToString());
                }
                listAges.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listAges.Items.Add(aux[i]);
                }
                aux.Clear();
                
                for (int i = 0; i < listEducation.Items.Count; i++)
                {
                    if (i != listNames.SelectedIndex)
                        aux.Add(listEducation.Items[i].ToString());
                }
                listEducation.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listEducation.Items.Add(aux[i]);
                }
                aux.Clear();
                
                for (int i = 0; i < listRelations.Items.Count; i++)
                {
                    if (i != listNames.SelectedIndex)
                        aux.Add(listRelations.Items[i].ToString());
                }
                listRelations.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listRelations.Items.Add(aux[i]);
                }
                aux.Clear();
                
                for (int i = 0; i < listOcupation.Items.Count; i++)
                {
                    if (i != listNames.SelectedIndex)
                        aux.Add(listOcupation.Items[i].ToString());
                }
                listOcupation.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listOcupation.Items.Add(aux[i]);
                }
                aux.Clear();
                
                for (int i = 0; i < listNames.Items.Count; i++)
                {
                    if (i != listNames.SelectedIndex)
                        aux.Add(listNames.Items[i].ToString());
                }
                listNames.Items.Clear();
                for (int i = 0; i < aux.Count; i++)
                {
                    listNames.Items.Add(aux[i]);
                }
                aux.Clear();
            }
        }
    }
}
